package com.teatang.tadmin.util;

import com.teatang.tadmin.core.domain.TreeObj;


import java.util.ArrayList;
import java.util.List;

public class TreeUtils {
    public static <E extends TreeObj> List<E> toTree(List<E> treeList, Long pid) {
        List<E> retList = new ArrayList<>();
        for (E parent : treeList) {
            if (pid.equals(parent.parentKey())) {
                retList.add(findChildren(parent, treeList));
            }
        }
        return retList;
    }

    private static <E extends TreeObj> E findChildren(E parent, List<E> treeList) {
        for (E child : treeList) {
            if (parent.primaryKey().equals(child.parentKey())) {
                if (parent.getTreeObjChild() == null) {
                    parent.setTreeObjChild(new ArrayList<E>());
                }
                parent.getTreeObjChild().add(findChildren(child, treeList));
            }
        }
        return parent;
    }
}
